package com.purong.purong.fragment;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.activity.SmallLoanDetialActivity;
import com.purong.purong.adapter.SmallLoanCollectAdapter;
import com.purong.purong.bean.BankLoanDetBean;
import com.purong.purong.bean.SmallLoanBean;
import com.purong.purong.bean.SmallLoanCollectBean;
import com.purong.purong.bean.SmallLoanDetBean;
import com.purong.purong.widget.LoadingView;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrCustomHandler;
import in.srain.cube.views.ptr.PtrDefaultCustomHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrPuRongLayout;

/**
 * Created by zengwenjie on 2017/12/4.
 */
public class SmallLoanCollectFragment extends BaseFragment{
    private ListView mListView;
    private SmallLoanCollectAdapter mAdapter;
    private List<SmallLoanBean> loanList = new ArrayList<>();
    private PtrPuRongLayout mPtrFrame;
    private LoadingView loadView;
    private int page = 1;
    @Override
    public int getRootViewId() {
        return R.layout.fragment_small_loan_collect;
    }

    @Override
    public void initView(View rootView) {
        loadView = (LoadingView) rootView.findViewById(R.id.loading_view);
        loadView.setNoResultToast("暂无收藏的贷款", "");
        loadView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getLoan(true);
            }

            @Override
            public void onRefresh() {

            }
        });
        mListView = (ListView) rootView.findViewById(R.id.list_view);
        mAdapter = new SmallLoanCollectAdapter(getActivity(), loanList);
        mAdapter.setOnLoanCollectListener(new SmallLoanCollectAdapter.OnLoanCollectListener() {
            @Override
            public void onLoan(int position) {
                Intent intent=new Intent(getActivity(),SmallLoanDetialActivity.class);
                intent.putExtra("LOAN",loanList.get(position));
                intent.putExtra("NEED_BACK",true);
                startActivityForResult(intent,1);
            }

            @Override
            public void onDelete(int position) {
                cancelFavourite(loanList.get(position).getSmall_product_id());
            }
        });
        mListView.setAdapter(mAdapter);
//        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent intent=new Intent(getActivity(),BankLoanDetialActivity.class);
//                intent.putExtra("LOAN",loanList.get(position));
//                startActivity(intent);
//            }
//        });
        mPtrFrame = (PtrPuRongLayout) rootView.findViewById(R.id.rotate_header_list_view_frame);
        mPtrFrame.setPtrHandler(new PtrCustomHandler() {
            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                if (loanList.size() == 0) {
                    return false;
                } else {
                    return PtrDefaultCustomHandler.checkContentCanBePulledUp(frame, content, footer);
                }

            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getLoan(false);

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getLoan(true);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
//                return (isRequesting||loanList.size()>0)?false:true;
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (resultCode==getActivity().RESULT_OK){
                SmallLoanDetBean bean=(SmallLoanDetBean)data.getSerializableExtra("LOAN");
                for (int i = 0; i <loanList.size() ; i++) {
                    if (loanList.get(i).getSmall_product_id().equals(bean.getSmall_product_id())){
                        if (bean.getIs_favorite().equals("1"))
                        loanList.remove(i);
                        break;
                    }

                }
                mAdapter.notifyDataSetChanged();
                if (loanList.size() == 0) {
                    loadView.noResult();
                }
            }
        }
    }

    private void cancelFavourite(String id) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("small_id", id);
        request(Contant.SMALL_FAVORITE_CANCEL, params, true, true);
    }

    private void getLoan(boolean clear){
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (clear){
            page=1;
            loanList.clear();
            mAdapter.notifyDataSetChanged();
            loadView.loading();
        }
        params.put("page", page+"");
        if (!request(Contant.USER_SMALL_FAVORITE, params, true)) {
            if (clear)
                loadView.fail();
            if (!hasDestroy())
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (mPtrFrame.isRefreshing()) {
                            mPtrFrame.refreshComplete();
                        }
                    }
                }, 100);
        }
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.USER_SMALL_FAVORITE)){
            if (mPtrFrame.isRefreshing()) {
                mPtrFrame.refreshComplete();
            }
            if (responseInfo.isRequestOk){
                try{
                    SmallLoanCollectBean bean= JSON.parseObject(responseInfo.content,SmallLoanCollectBean.class);
                    if (bean != null && bean.getSmall_list() != null) {
                        if (bean.getSmall_list().size() > 0)
                            page++;
                        loanList.addAll(bean.getSmall_list());
                        mAdapter.notifyDataSetChanged();

                    }
                    if (loanList.size() == 0) {
                        loadView.noResult();

                    } else {
                        loadView.finish();
                    }
                }catch (Exception e){
                    if (page == 1) {
                        loadView.fail();
                    }
                }
            }else {
                if (page == 1) {
                    loadView.fail();
                }
            }
        }else if (responseInfo.url.equals(Contant.SMALL_FAVORITE_CANCEL)){
            if (responseInfo.isRequestOk){
                try{
                    String id=responseInfo.params.get("small_id");
                    for (int i = 0; i <loanList.size() ; i++) {
                        if (loanList.get(i).getSmall_product_id().equals(id)){
                            loanList.remove(i);
                            break;
                        }

                    }
                    mAdapter.notifyDataSetChanged();
                    if (loanList.size() == 0) {
                        loadView.noResult();

                    }
                }catch (Exception e){

                }
            }
        }
    }

    @Override
    public void initData() {
        getLoan(true);
    }
}
